package chat

import (
	"sort"
	"time"
)

const (
	slotMax = 5
)

type stats struct {
	slot []*slot //time slot
}

type slot struct {
	ts   int64
	data *TopRank
}

func (s *stats) Top() string {
	count := make(map[string]*Item)
	ts := time.Now().Unix()
	for i := len(s.slot) - 1; i >= 0; i-- {
		if s.slot[i].ts > ts-slotMax {
			//near 5 second
			top5 := s.slot[i].data.Range(1, 5)
			for _, t := range top5 {
				if _, ok := count[t.ID]; ok {
					count[t.ID].Value += t.Value
				} else {
					count[t.ID] = t
				}
			}
		}
	}
	if len(count) == 0 {
		return ""
	}
	top := make([]*Item, 0, len(count))
	for k := range count {
		top = append(top, count[k])
	}
	sort.Sort(sort.Reverse(ItemSort(top)))
	item := top[0]
	return item.ID
}

func (s *stats) CountWords(words []string) {
	ts := time.Now().Unix()
	var _slot *slot
	for i := len(s.slot) - 1; i >= 0; i-- {
		if s.slot[i].ts == ts {
			_slot = s.slot[i]
			break
		}
	}
	if _slot == nil {
		_slot = &slot{ts: ts, data: NewTopRank()}
		s.slot = append(s.slot, _slot)
		if len(s.slot) > slotMax {
			s.slot = s.slot[len(s.slot)-slotMax:]
		}
	}
	for _, w := range words {
		_slot.data.Update(&Item{ID: w, Value: 1})
	}
}
